package com.zrc.japktool.ui.view;

import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;

public class LogTextField0 extends ScrollPane {
    // 日志级别枚举（颜色+前缀）
    public enum LogLevel {
        DEBUG(Color.GRAY, "[DEBUG]"),
        INFO(Color.BLACK, "[INFO]"),
        WARN(Color.ORANGE, "[WARN]"),
        ERROR(Color.RED, "[ERROR]");

        private final Color color;
        private final String prefix;

        LogLevel(Color color, String prefix) {
            this.color = color;
            this.prefix = prefix;
        }

        public Color getColor() {
            return color;
        }

        public String getPrefix() {
            return prefix;
        }
    }

    private VBox logContainer; // 垂直布局：承载所有日志行
    private Set<LogLevel> enabledLevels = EnumSet.allOf(LogLevel.class);
    private final SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private int maxLogLines = 1000;
    private List<TextField> logFields = new ArrayList<>(); // 存储所有日志TextField
    private boolean autoScroll = true; // 自动滚动开关（默认开启）

    public LogTextField0() {
        initStyle();
        initCopySupport();
        initAutoScrollListener();
    }

    /**
     * 初始化基础样式：滚动面板 + 垂直日志容器
     */
    private void initStyle() {
        logContainer = new VBox(0); // 日志行之间无间距
        logContainer.setPadding(new javafx.geometry.Insets(8));
        logContainer.setPrefWidth(USE_COMPUTED_SIZE);
        // 关键修复1：设置VBox的minHeight为确保内容能完整显示
        logContainer.setMinHeight(VBox.USE_COMPUTED_SIZE);
        setContent(logContainer);
        setFitToWidth(true);
        setStyle("-fx-font-family: 'Microsoft YaHei', 'SimSun'; -fx-font-size: 12px;");
    }

    /**
     * 修复自动滚动逻辑，确保滚动到底部
     */
    private void initAutoScrollListener() {
        logContainer.getChildren().addListener((ListChangeListener.Change<? extends javafx.scene.Node> change) -> {
            while (change.next()) {
                if (autoScroll && change.wasAdded() && !logContainer.getChildren().isEmpty()) {
                    // 关键修复2：使用双层Platform.runLater确保布局已完全更新
                    Platform.runLater(() -> Platform.runLater(() -> {
                        logContainer.layout();
                        // 强制刷新滚动面板布局
                        this.layout();
                        // 滚动到底部
                        setVvalue(1.0);
                    }));
                }
            }
        });
    }

    /**
     * 初始化复制功能
     */
    private void initCopySupport() {
        logContainer.setFocusTraversable(true);

        logContainer.setOnKeyPressed(event -> {
            if (event.isControlDown() && event.getCode() == KeyCode.C) {
                copySelectedText();
            }
        });

        logContainer.setOnMouseClicked(event -> {
            logContainer.requestFocus();
        });
    }

    /**
     * 复制选中的文本到剪贴板
     */
    private void copySelectedText() {
        StringBuilder sb = new StringBuilder();
        boolean hasSelected = false;

        for (TextField field : logFields) {
            String selectedText = field.getSelectedText();
            if (selectedText != null && !selectedText.isEmpty()) {
                sb.append(selectedText);
                hasSelected = true;
            }
            else if (field.isFocused() && field.getSelection().getStart() == 0
                    && field.getSelection().getEnd() == field.getText().length()) {
                sb.append(field.getText());
                hasSelected = true;
            }

            if (hasSelected && logFields.indexOf(field) != logFields.size() - 1) {
                sb.append("\n");
                hasSelected = false;
            }
        }

        if (sb.length() > 0) {
            Clipboard clipboard = Clipboard.getSystemClipboard();
            ClipboardContent content = new ClipboardContent();
            content.putString(sb.toString());
            clipboard.setContent(content);
        }
    }

    /**
     * 添加日志
     */
    public void addLog(LogLevel level, String message) {
        if (!enabledLevels.contains(level)) return;

        Platform.runLater(() -> {
            String time = timeFormatter.format(new Date());
            String logEntry = String.format("[%s] %s %s", time, level.getPrefix(), message);

            TextField logField = new TextField(logEntry);
            logField.setEditable(false);
            logField.setFocusTraversable(true);
            logField.setPrefWidth(USE_COMPUTED_SIZE);
            logField.setMaxWidth(Double.MAX_VALUE);
            logField.setStyle(
                    "-fx-background-color: transparent; " +
                            "-fx-border-width: 0; " +
                            "-fx-text-fill: " + toHexString(level.getColor()) + "; " +
                            "-fx-font-family: 'Microsoft YaHei', 'SimSun'; " +
                            "-fx-font-size: 12px; " +
                            "-fx-padding: 1 0 1 0;"
            );

            trimExcessLogs();
            logContainer.getChildren().add(logField);
            logFields.add(logField);

            // 关键修复3：添加日志后额外触发一次滚动检查
            if (autoScroll) {
                scrollToBottom();
            }
        });
    }

    /**
     * 新增：专用滚动到底部方法，确保可靠性
     */
    private void scrollToBottom() {
        Platform.runLater(() -> {
            // 先让容器布局更新
            logContainer.applyCss();
            logContainer.layout();
            // 再让滚动面板更新
            this.applyCss();
            this.layout();
            // 最后滚动到底部
            this.setVvalue(1.0);
        });
    }

    /**
     * 将Color转换为十六进制字符串
     */
    private String toHexString(Color color) {
        return String.format("#%02X%02X%02X",
                (int) (color.getRed() * 255),
                (int) (color.getGreen() * 255),
                (int) (color.getBlue() * 255)
        );
    }

    /**
     * 修剪日志行数
     */
    private void trimExcessLogs() {
        while (logContainer.getChildren().size() >= maxLogLines) {
            logContainer.getChildren().remove(0);
            logFields.remove(0);
        }
    }

    // ------------------- 对外暴露的控制方法 -------------------
    public void clearLogs() {
        logContainer.getChildren().clear();
        logFields.clear();
        setVvalue(0.0);
    }

    public void setEnabledLevels(Set<LogLevel> enabledLevels) {
        this.enabledLevels = enabledLevels != null ? enabledLevels : EnumSet.allOf(LogLevel.class);
    }

    public void setMaxLogLines(int maxLogLines) {
        this.maxLogLines = Math.max(maxLogLines, 100);
        trimExcessLogs();
    }

    public void setAutoScroll(boolean autoScroll) {
        this.autoScroll = autoScroll;
        if (autoScroll) {
            // 关键修复4：重新开启自动滚动时使用专用滚动方法
            scrollToBottom();
        }
    }

    // 快捷添加日志的方法
    public void debug(String msg) {
        addLog(LogLevel.DEBUG, msg);
    }

    public void info(String msg) {
        addLog(LogLevel.INFO, msg);
    }

    public void warn(String msg) {
        addLog(LogLevel.WARN, msg);
    }

    public void error(String msg) {
        addLog(LogLevel.ERROR, msg);
    }
}
